package com.x.erp.service;

import com.alibaba.fastjson.JSON;
import com.x.erp.dao.UserDao;
import com.x.erp.model.User;
import com.x.erp.thirdparty.ZhiTongData;
import com.x.erp.thirdparty.ZhiTongInfo;
import com.x.erp.util.Constant;
import com.x.erp.util.SignatureUtils;
import com.x.erp.util.ZhiTongApi;
import com.x.erp.util.ZhiTongResult;
import com.x.framework.service.BaseService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.List;

@Component
public class ZhiTongService extends BaseService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UserDao userDao;

	@Autowired
	private ZhiTongApi zhiTongApi;

	// 用户信息同步
	public void insertShop(User user) {
		if (user == null && StringUtils.isNotEmpty(user.getUserId())){
			logger.info("获取车商用户信息失败！");
			return;
		}
		// 查询用户信息
		User userInfo = new User();
		userInfo.setUserId(user.getUserId());
		List<User> users = null;
		try {
			users = userDao.selectUserList(userInfo);
			if (users == null || users.size() == 0){
				logger.info("获取车商用户信息失败！");
				return;
			}
		} catch (Exception e) {
			logger.error("获取车商用户信息失败！", e);
			return;
		}
		// 封装数据
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZhiTongData zhiTongData = new ZhiTongData();
		zhiTongData.setApplicationID(Constant.ZHITONG_APPLICATIONID);
		zhiTongData.setIsOrgLeader("0");
		zhiTongData.setMobile(users.get(0).getUserMobile());
		zhiTongData.setThirdPartyAccount(users.get(0).getShopId());
		zhiTongData.setUserName(users.get(0).getUserName());
		zhiTongData.setOrgCode(Constant.ZHITONG_ORGCODE);
		String sign = SignatureUtils.signOfZhiTong(JSON.toJSONString(zhiTongData), Constant.ZHITONG_PRIVATE_KEY);

		ZhiTongInfo zhiTongInfo = new ZhiTongInfo();
		zhiTongInfo.setSendTime(sdf.format(this.getDate(0)));
		zhiTongInfo.setSign(sign);
		zhiTongInfo.setData(zhiTongData);
		try {
			ZhiTongResult zhiTongResult = zhiTongApi.insertShop(zhiTongInfo);
			if (zhiTongResult == null){
				logger.info("智通同步用户失败！");
				return;
			}
			if (StringUtils.isNotEmpty(zhiTongResult.getState()) && !zhiTongResult.getState().equals("1")){
				logger.info("智通同步用户失败，提示码：" + zhiTongResult.getMsgCode() + "  ，提示信息：" + new String(zhiTongResult.getMsg().getBytes(),"UTF-8"));
				return;
			}
			logger.info("智通同步用户成功！ 商户ID：" + users.get(0).getShopId());
		} catch (Exception e) {
			logger.error("智通同步用户失败！", e);
			return;
		}
	}

}
